<template>
  <div>
    <div style="text-align: left;">
      <router-link to="/home"><el-i class="fas fa-home" style="color: black;"></el-i></router-link> 
    </div>
    <h1 style="color: black;">全部博文</h1>
    <div class="container">
      <el-table :data="posts" style="width: 100%" border stripe>
        <el-table-column label="标题" prop="PostTitle" align="left">
          <template #default="scope">
            <el-link
              type="primary"
              underline
              @click="goToPost(scope.row.PostID)"
            >
              {{ scope.row.PostTitle }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="作者名" prop="UserName" align="center"></el-table-column>
        <el-table-column label="发布时间" prop="Post_Date" align="center" :formatter="formatDate"></el-table-column>
        <!-- <el-table-column label="点赞数" prop="LikeCount" align="center"></el-table-column> -->
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'; // 引入 ref 和生命周期钩子
import instance from '../api/server'; // 引入 axios 实例
import { useRouter } from 'vue-router'; // 路由

// 定义变量
const posts = ref([]); // 保存博文数据
const router = useRouter(); // 路由实例

// 获取博文数据
const getPosts = async () => {
  try {
    const response = await instance.get('/myinfo/blog/getallpost');
    console.log(JSON.stringify(response.data, null, 2));  
    if (response.data.status === 0) {
      posts.value = response.data.data; // 赋值后端返回的博文数据
    } else {
      console.error('获取博文失败:', response.data.message);
    }
  } catch (error) {
    console.error('获取博文数据失败:', error);
  }
};

// 格式化日期
const formatDate = (row, column, cellValue) => {
  if (!cellValue) return '-';
  const date = new Date(cellValue);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 跳转到博文详情
const goToPost = (postID) => {
  router.push(`/bokeinfo/${postID}`).then(() => {
    window.location.reload();
  });
};

// 页面加载时调用获取博文方法
onMounted(() => {
  getPosts();
});
</script>

<style scoped>
.container {
  margin: 20px auto;
  padding: 20px;
}
h1 {
  text-align: center;
  margin-bottom: 20px;
}
</style>
